<?php
namespace pay;
use \think\Db;
use think\facade\Log;

/**
 * 支付宝支付类
 */
class Alipay {
    //是否沙盒环境
    private $is_sandbox = false;
    //沙盒地址
    private $sandurl = 'https://openapi.alipaydev.com/gateway.do';
    //正式地址
    private $apiurl  = 'https://openapi.alipay.com/gateway.do';
    //网关地址（设置为公有，外部需要调用）
    public $gateway;
    //支付宝的APPID
    private $appid = 2021004129633092;
    //应用私钥
//    private $rsaPrivateKey = '商户设置的私钥';
    private $rsaPrivateKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoygSFEPoEqfUPrc+yjyPpAfL5wMt3PqUnc5skTzR0N9yr0N936TCgFKTGVfugUcsagf1g4KPMSOko8Uy5ywsfm8pdQ6XIKkQh9lgkbt2UCs9u0ubat/nNzAlFuLRiBRxwXj/TodsiaVXoH3ZJHq3EtNVXRgST0ommIB6wirW7Gpxz19nSI9kR53tpd+iH4pIvqbvurGs8F/0ZXOZ59L09ee6/+qXvVePECsg46noV3QuMC0lsl+k021PJcoj0KcJO2YJe9lLJBHTNRL9GpnnHx7E2+tFXC16ChqSw7VPIU6UBBiacAFnPlUgtHH4AjhH0Ha8PX7z6t4KF+yx5EPs4QIDAQAB';
    //支付宝公钥
    private $alipayPublicKey= 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgkU3mqFJNh/R5iw1I+O5b+yCpB2fwccnPeq+wIZLHbTeHYQHNAgZd+PigioYIyGYVXvoch17e60A8CvImaTPKbFhx4aEl5DOFlZIYubRyxFkjdrbuoDZO6mcbNadaNdHAV9w90jtbdm5vSxiOz4J4RhAqX4Y7capmsTRsivLnGC0TSnstmC0YjEbyOGwCsruLwh4U/04FQ9PnrkVcGFNhGyP5ULVK4NJVS5AnPaKKc9DPegP/yJnm87C2rMdi7Q/0pM09+Dk0txhKJIJTmn1OwWGyH+8SPZF0AXQVbUcZqRjEzg26dlr5VS2F/0M47OQg0uF8IjKGEszitWIGVkDlQIDAQAB';
    private $charset = 'utf-8';
    private $scope;
    private $auth_code;
    private $notify_url;

    public function setAppid($appid)
    {
        $this->appid = $appid;
    }

    public function setRsaPrivateKey($rsaPrivateKey)
    {
        $this->rsaPrivateKey = $rsaPrivateKey;
    }

    public function setAlipayPublicKey($alipayPublicKey)
    {
        $this->alipayPublicKey = $alipayPublicKey;
    }
    public function setScope($scope)
    {
        $this->scope = $scope;
    }
    public function setAuthCode($authCode)
    {
        $this->auth_code = $authCode;
    }
    //构造方法
    public function __construct($account=null){
        if($account!=null){
            //如果是沙箱测试
            if($this->is_sandbox){
                $this->gateway = $this->sandurl;
                $this->appid = '2021000117612368';
                $this->rsaPrivateKey ='MIIEowIBAAKCAQEAgAWVzlJRyrsZQyoVSjInQQZa2NtOlhLpH5osB04qB3PglUP5PdObbgBoq5xZFHeYfw7GBQzqKxGsHu3CPB7Y+SZyBZcORDtcMY9Nmul0GMn5hNqM40hpl1TfAbkkXcuSzAZTZ0n3VkRhUYbhphNlcYFFPPjaqhm0o+VJ1SZ8N6lEcvvSVSL89gTcAjlGfFVxanFpWtvu8tAQLuFQoK/B72yFsjbn+TnmW9v34DSiGvRKz4xlw7qFpOVyNxgrmN1JH1IMwkI0fW2juBdSmu3N1oB7ok5D9WgWFqvNkvWfQcnojwaCNa5/gXPKUgsVgU+LsreZa0Gy1K0JDxgGPcjQXwIDAQABAoIBAD3JdEnFtTARKNofn3LVzdg2RvZOshkAO39DG2jTMrmyFXw0+D/8txFaJSpeJSgZqIH6EVwypXnv55Bt08bMZI+rHHDSPNJ1i8NnlF7luWCValXSXRj8w+mDzrW4M3MJY2oQy4QYUMVT71w3qwRKbDVh3JbWzEI4cdSAPygekOkTmtY7C8rg/CKkL1IK8KX8qCSRfMzIH2dKenxffgANxprXVaucf+d/dwbwtcyIRNOYN3cxRrSXPnUNSyUvJ8IJc96zCMLXqU4LmBgI2OvC8t3OPkp35CTUNC/7L9VsTNL1p7NFxVbbAkBXLbbnp7Tcw8PPuEpSJJLOhxvYLGDI/xECgYEAyrH9pB6xxAdnkBLHYn2geWSnAfi+VCq+cfpqLCsffgDl5S5NiE2T2lbOy7uJ1fypjt24jimBhriBf4yqo8CeL/FmD9zw23/wfwXAyixP+UXy3nt6M9DxEG+bFA59hN6XgXCHVMkVCzPC2dmN+DucpXYJdcqaFVTJDm40InE96o0CgYEAobBen5q3KK7mMA8nR0NpLfLGEh+QEAOCUJjHBebLaG3GD3RWk4ScO7hTkH5cFZfM72RpEo6iDuXSCQQu6Tu08RD88LEP6vwOncNwsylJt3yFSvrYq+O2pUXRYsP4ZomzyA55zGCJhGYW/7wG1G0DfXw4EbVB65QqBYT5ICc2QZsCgYEAwVxwoXrijCWgJvGzIQLE7mkVZK0dK/+ms+Z2GHJ+1V4X8bxtHCUdccEz/2iFQgyI2BAtefigZptmdf4D3rjmbsfzXBih8FMpYpNjabpCBIM1AAZ8+idNgCdnogd8uB78Gu/1Oe2lVI1pSRbf9zku4y0qMyM2QDkkn86Dj4PF1BUCgYASkBEM+dI1VX8P3W2A/PhCUjDzO7RqYjy/zAptXwXTQ2cNtymJXhwhrxPI7vjbccYRZdG6U62/UBtA9b39AOHRG0Yuy+Ur8SwsaJezufXAnwceiJX/hfEeIFndoOoPu5dsTF0nXZ3sGVxil8+g67MO4Qf+4HRk+2mnoJCJZHcSKQKBgD7fWkvqEJ27ii5orxRmrVcmHGArOwN/w1nY7vAfWu8kScp/EDhbMWt+AvH2XFZJhmo2wxSkBamFMAK2kKT7WTviTiERF2iPFnv23Lm1shKTiR5Gz2fIfTDFwYyyhHo2qkKsyIntWp1eW/1m1HxU/oHR/uB6MnmG+jjmY7Jz5mxg';
                $this->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs9AE75V+F242HcN/SlcGUxUNv3zGpXjai4u2ZMkOL1nolr4/v4BGEsE8tLaYq6lecG/of5taQ27WbWXB5PMB3s6emesTEn5yvZPh/HqmKACHi7js+Dtu123J/z0DyCukMm1ZHJe7jT9VEU9w4gIdNi64VxdaRF3ZMT6DXnboUEegyRKGmJc58h+O30P/UYqdCW/Gl+380o80e6Fs0rX33AixkNTRNgnQ3n2er1Nrqan/9sfUCnqqxgpc1+GTT+vyn3x4Xwvch2pRIkcK4BFCrWVVMKVXx/icj1njTVwWm1KYrXDVYrxf4ZLgpMHyW3SfhnXFKuxvSYnvm5EHjxtNEQIDAQAB';
            }else{
                $this->gateway = $this->apiurl;
                $this->appid = $account['appid'];
                $this->rsaPrivateKey = $account['privateKey'];
                $this->alipayPublicKey = $account['publicKey'];
            }
        }
    }
    /**
     *
     * 1.发起电脑网站支付
     * $params 传输的数据
     */
    public function pcPay($params){
        //商品名称
        $subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识，订单编号（必须）
            'product_code'=>'FAST_INSTANT_TRADE_PAY',
            'total_amount'=>$params['money'], //付款金额，单位:元
            'subject'=>$subject,  //订单标题
            "timeout_express" =>"5m",//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.page.pay',//接口名称
            'format' => 'JSON',
            'return_url' => $params['return_url'],//同步通知地址
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return $this->buildRequestForm($this->gateway,$commonConfigs);
    }
    /**
     *
     * 2.发起手机网站支付
     * $params 传输的数据
     */
    public function wapPay($params){
        //商品名称
        $subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识，订单编号（必须）
            'product_code'=>'QUICK_WAP_WAY',
            'total_amount'=>$params['money'], //付款金额，单位:元
            'subject'=>$subject,  //订单标题
            "timeout_express" =>"5m",//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.wap.pay',//接口名称
            'format' => 'JSON',
            'return_url' => $params['return_url'],//同步通知地址
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return $commonConfigs;
    }
    /**
     *
     * 3.发起当面付
     * $params 传输的数据
     */
    public function facePay($params){
        $biz_content = $params;
//        //商品名称
//        $subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
//        //请求参数的集合，参考https://mp.csdn.net/editor/html/113599448
//        $biz_content = [
//            "scene" => "bar_code",//支付场景 条码支付，取值：bar_code 声波支付，取值：wave_code（必须）
//            "out_trade_no" => $params['pay_id'],//唯一标识，订单编号（必须）
//            //"auth_code" => $params['auth_code'],//支付授权码（商户签约模式时，为必须参数）
//            "total_amount" => $params['money'],//订单金额（可选）
//            "subject" => $subject,//商品名称
//            //"seller_id" => '',	//如果该值为空，则默认为商户签约账号对应的支付宝用户ID
//            "timeout_express" =>"5m",//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天
//        ];
        $notify_url = array_key_exists('notify_url',$params) ? $params['notify_url'] : $this->notify_url;
        //公共请求参数
        $param = [
            'app_id' => $this->appid,//支付宝分配给开发者的应用ID
//            'method' => 'alipay.trade.precreate',//接口名称
            'method' => 'alipay.trade.pay',//接口名称
            //'format' => 'JSON',//仅支持JSON
            'charset' => 'utf-8',//请求使用的编码格式
            'sign_type' => 'RSA2',//商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            'sign' => '',//商户请求参数的签名串
            'timestamp' => date('Y-m-d H:i:s', time()),//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
            'version' => '1.0',//调用的接口版本，固定为1.0
            'notify_url' => $notify_url,//异步通知地址，支付宝服务器主动通知商户服务器里指定的页面http/https路径
            //'app_auth_token' => '',//app_auth_token
            'biz_content' => json_encode($biz_content),	//请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递
        ];
        //组合生成签名参数
        $signdata = [];
        $signdata['app_id'] = $param['app_id'];
        $signdata['method'] = $param['method'];
        $signdata['charset'] = $param['charset'];
        $signdata['sign_type'] = $param['sign_type'];
        $signdata['timestamp'] = $param['timestamp'];
        $signdata['version'] = $param['version'];
        $signdata['notify_url'] = $param['notify_url'];
        $signdata['biz_content'] = $param['biz_content'];
        //生成签名
        $sign = $this->generateSign($signdata, 'RSA2');
        $param['sign'] = $sign;
        //echo "<pre>";
        //var_dump($param);die;
        //发起请求
        $content = $this->file_post($this->gateway,$param);
        $alipayData  = json_decode($content, true);
        //公共响应参数
//        $responseData = $alipayData['alipay_trade_precreate_response'];
        $responseData = $alipayData['alipay_trade_pay_response'];
        return $responseData;
    }
    /**
     *
     * 4.发起APP付（JSAPI）
     * $params 传输的数据
     */
    public function appPay($params){
        //商品名称
        $subject=isset($params['subject']) && !empty($params['subject']) ? $params['subject'] : "购买商品";
        //请求参数
        $requestConfigs = array(
            'out_trade_no'=>$params['pay_id'],//唯一标识，订单编号（必须）
            'total_amount'=>$params['money'], //付款金额，单位:元
            'subject'=>$subject,  //订单标题
            'product_code'=>'QUICK_MSECURITY_PAY', //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
            'timeout_express'=>'5m',//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
            //'store_id'=>'', //商户门店编号。该参数用于请求参数中以区分各门店，非必传项。
            //'extend_params'=>array(
            //	'sys_service_provider_id'=>''//系统商编号，该参数作为系统商返佣数据提取的依据，请填写系统商签约协议的PID
            // )
        );
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.trade.app.pay',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'notify_url' => $params['notify_url'],//异步通知地址
            'biz_content'=>json_encode($requestConfigs),
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return http_build_query($commonConfigs);
    }
    /**
     *
     * 5.支付查询接口
     * @param  data   支付宝响应的参数集合
     * @param  status 要验证的状态
     * WAIT_BUYER_PAY 交易创建等待买家付款
     * TRADE_CLOSED   未付款交易超时关闭或支付完成后全额退款
     * TRADE_SUCCESS  交易支付成功
     * TRADE_FINISHED 交易结束不可退款
     */
    public function orderquery($data , $status=''){
        $biz_content = [
            'out_trade_no' => $data['out_trade_no'],
            'trade_no' => $data['trade_no'],
            //'org_pid' => '',
        ];

        $param = [
            'app_id' => $this->appid,
            'method' => 'alipay.trade.query',
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'sign' => '',
            'timestamp' => date('Y-m-d H:i:s',  time()),
            'version' => '1.0',
            'biz_content' => json_encode($biz_content),
        ];

        //组合签名数组
        $signdata = [];
        $signdata['app_id'] = $param['app_id'];
        $signdata['method'] = $param['method'];
        $signdata['charset'] = $param['charset'];
        $signdata['sign_type'] = $param['sign_type'];
        $signdata['timestamp'] = $param['timestamp'];
        $signdata['version'] = $param['version'];
        $signdata['biz_content'] = $param['biz_content'];

        //生成签名
        $sign = $this->generateSign($signdata, 'RSA2');
        $param['sign'] = $sign;
        $content = $this->file_post($this->gateway,$param);
        $alipayData  = json_decode($content, true);
        //公共响应参数
        $responseData = $alipayData['alipay_trade_query_response'];
        return $responseData;
        if($responseData['code'] == 10000){
            if($responseData['trade_status'] == $status){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

    /**
     *
     * 5.交易撤销
     * @param  data   支付宝响应的参数集合
     * @param  status 要验证的状态
     * WAIT_BUYER_PAY 交易创建等待买家付款
     * TRADE_CLOSED   未付款交易超时关闭或支付完成后全额退款
     * TRADE_SUCCESS  交易支付成功
     * TRADE_FINISHED 交易结束不可退款
     */
    public function cancelPay($orderid){
        $biz_content = [
            'out_trade_no' => $orderid,
        ];

        $param = [
            'app_id' => $this->appid,
            'method' => 'alipay.trade.close',
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'sign' => '',
            'timestamp' => date('Y-m-d H:i:s',  time()),
            'version' => '1.0',
            'biz_content' => json_encode($biz_content),
        ];

        //组合签名数组
        $signdata = [];
        $signdata['app_id'] = $param['app_id'];
        $signdata['method'] = $param['method'];
        $signdata['charset'] = $param['charset'];
        $signdata['sign_type'] = $param['sign_type'];
        $signdata['timestamp'] = $param['timestamp'];
        $signdata['version'] = $param['version'];
        $signdata['biz_content'] = $param['biz_content'];

        //生成签名
        $sign = $this->generateSign($signdata, 'RSA2');
        $param['sign'] = $sign;
        $content = $this->file_post($this->gateway,$param);
        $alipayData  = json_decode($content, true);
        //公共响应参数
        $responseData = $alipayData['alipay_trade_close_response'];
        dd($responseData);
        return $responseData;
        if($responseData['code'] == 10000){
            if($responseData['trade_status'] == $status){
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }
    /**
     * 6.获取用户信息
     * @return array
     */
    public function doGetUserInfo($token)
    {
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.user.info.share',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'auth_token'=>$token,
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->file_post('https://openapi.alipay.com/gateway.do?charset='.$this->charset,$commonConfigs);
        return json_decode($result,true);
    }
    /**
     * 支付宝异步通知
     * @param $data 通知的数据
     */
    public function notify($data){
        $falg=false;
        $param = $data;
        //不参与签名
        unset($param['sign']);
        unset($param['sign_type']);
        $rst = $this->rsaCheck($param, $data['sign'] , $data['sign_type']);
        if(!$rst){
            //file_put_contents(LOG_PATH .'alipaynotify.log', '验签失败\r\n' , FILE_APPEND );
            return false;
        }
        //查询支付订单状态
        try{
            $rst = $this->orderquery($data, 'TRADE_SUCCESS');
        } catch (\Exception $e) {
            //printLog("查询支付订单状态失败：".$e);
        }
        if($rst){
            $falg=true;
        }else {
            //file_put_contents(LOG_PATH .'alipaynotify.log', '查询订单状态错误\r\n', FILE_APPEND);
            $falg=false;
        }
        return $falg;
    }
    /**
     * 获取access_token和user_id
     * @return array
     */
    public function doAuth()
    {
        $commonConfigs = array(
            //公共参数
            'app_id' => $this->appid,
            'method' => 'alipay.system.oauth.token',//接口名称
            'format' => 'JSON',
            'charset'=>$this->charset,
            'sign_type'=>'RSA2',
            'timestamp'=>date('Y-m-d H:i:s'),
            'version'=>'1.0',
            'grant_type'=>'authorization_code',
            'code'=>$this->auth_code,
        );
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        $result = $this->file_post('https://openapi.alipay.com/gateway.do?charset='.$this->charset,$commonConfigs);
        return json_decode($result,true);
    }
    /**
     * 获取access_token和user_id
     */
    public function getToken()
    {
        //通过code获得access_token和user_id
        if (!isset($_GET['auth_code'])){
            //触发返回code码
            $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
            $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
            if($_SERVER['QUERY_STRING']) $baseUrl = $baseUrl.'?'.$_SERVER['QUERY_STRING'];
            $url = $this->createAuthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码，以获取openid
            $this->setAuthCode($_GET['auth_code']);
            return $this->doAuth();
        }
    }
    /**
     * 构造获取token的url连接
     * @param string $redirectUrl 服务器回跳的url，需要url编码
     * @return 返回构造好的url
     */
    protected function createAuthUrlForCode($redirectUrl)
    {
        $urlObj["app_id"] = $this->appid;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["scope"] = $this->scope;
        $urlObj["state"] = 123456;
        $bizString = $this->ToUrlParams($urlObj);
        return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?".$bizString;
    }
    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    protected function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    protected function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }

    protected function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    protected function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
    /**
     *
     * 校验$value是否非空
     */
    protected function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    /**
     *
     * 签名函数
     */
    protected function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    /**
     *
     * 验签函数（用于查询支付宝数据）
     */
    protected function rsaCheck($data, $sign,$type = 'RSA'){
        $public_key = $this->alipayPublicKey;
        $search = [
            "-----BEGIN PUBLIC KEY-----",
            "-----END PUBLIC KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];
        $public_key=str_replace($search,"",$public_key);
        $public_key=$search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
        $res=openssl_get_publickey($public_key);
        if($res)
        {
            if($type == 'RSA'){
                $result = (bool)openssl_verify($this->getSignContent($data), base64_decode($sign), $res);
            }elseif($type == 'RSA2'){
                $result = (bool)openssl_verify($this->getSignContent($data), base64_decode($sign), $res,OPENSSL_ALGO_SHA256);
            }
            openssl_free_key($res);
        }else{
            return false;
        }
        return true;
    }
    /**
     * file_get_contents发送post请求
     * @param url       请求地址
     * @param postData  要传递的post数据
     */
    protected function file_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 300
            // 超时时间（单位:s）
        ));
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        trace($result);
        //去空格
        $result = trim($result);
        //转换字符编码
        $result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');
        //解决返回的json字符串中返回了BOM头的不可见字符（某些编辑器默认会加上BOM头）
        $result = trim($result,chr(239).chr(187).chr(191));
//        wyuLog('cashier.txt', "请求结果：" . var_export($return, true));
        return $result;
    }
    /**
     * curl发送post请求
     * @param url       请求地址
     * @param postData  要传递的post数据
     */
    protected function curl_post($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @param $url 请求地址
     * @param $params 请求参数数组
     * @return 提交表单HTML文本
     */
    protected function buildRequestForm($url,$params) {

        $sHtml = "正在跳转至支付页面...<form id='alipaysubmit' name='alipaysubmit' action='".$url."?charset=".$this->charset."' method='POST'>";
        foreach($params as $key=>$val){
            if (false === $this->checkEmpty($val)) {
                $val = str_replace("'","&apos;",$val);
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
}
?>
